package com.ls.fw.token.service;

import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.CacheManager;

import com.ls.fw.token.service.impl.AbstractTokenManager;

/**
 * 使用MySQL存储Token
 */
public class MapTokenManager extends AbstractTokenManager {


    private Cache  cache;
    @Autowired
    public MapTokenManager(CacheManager cacheManager) {
        this.cache = cacheManager.getCache("cache");
    }
    @Override
    public void delSingleRelationshipByKey(String key) {
    	cache.evict(key);
    }

    @Override
    public void delRelationshipByToken(String token) {
        cache.evict(token);
    }

    @Override
    protected void createMultipleRelationship(String key, String token) {
    	cache.put(key, token);
        cache.put(token, key);
    }

    @Override
    protected void createSingleRelationship(String key, String token) {
    	cache.put(key, token);
        cache.put(token, key);
    }

    @Override
    public String getKeyByToken(String token) {
    	ValueWrapper v = cache.get(token);
    	if(v==null){
    		return null;
    	}
    	return v.toString();
    }

    @Override
    protected void flushExpireAfterOperation(String key, String token) {
        cache.put(key, token);
        cache.put(token, key);
    }
    @Override
    public String createToken(String key) {
        //使用uuid作为源token
        String token =  UUID.randomUUID().toString().replace("-", "");
        //存储到redis并设置过期时间
        this.createRelationship(key, token);
        return token;
    }
	@Override
	public String getToken(String key, boolean createIFNoExist) {
		// TODO Auto-generated method stub
		return null;
	} 
}
